package com.blue.firecat.controller;

import com.alibaba.fastjson.JSON;
import com.blue.firecat.contants.Contants;
import com.blue.firecat.contants.Result;
import com.blue.firecat.entity.Order;
import com.blue.firecat.serivce.OrderService;
import com.blue.firecat.utils.controller.BaseController;
import com.blue.firecat.utils.date.DateUtil;
import com.blue.firecat.utils.excel.ExportExcel;
import com.blue.firecat.vo.OrderVo;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import org.apache.commons.collections.CollectionUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;

/**
 * @描述
 * @时间 2017-6-23 16:53
 * @作者 肖亦鸣
 */
@Controller
@RequestMapping("order")
public class OrderController extends BaseController {
    private static Logger logger = LogManager.getLogger(OrderController.class.getName());

    @Autowired
    OrderService orderService;

    @RequestMapping("orderList")
    public String orderList(OrderVo orderVo) {
        logger.info("orderVo:{}", JSON.toJSONString(orderVo));
        Result<List<Order>> result = orderService.selectByExample(orderVo, getUserBySession());
        request.setAttribute(Contants.ORDERS, result.getData());
        request.setAttribute(Contants.OBJECT, orderVo);
        logger.info("result:{}", JSON.toJSONString(result));
        logger.info("orderVo:{}", JSON.toJSONString(orderVo));
        return "order-list";
    }

    @RequestMapping("orderAdd")
    public String orderAdd() {
        return "order-add";
    }

    @RequestMapping(value = "addOrder", method = RequestMethod.POST)
    public String addOrder(Order order) {
        order.setCreateTime(DateUtil.getInstance().getDateByString(order.getCreateTimeString()));
        logger.info("order:{}", JSON.toJSONString(order));
        Result<Order> result = null;
        try {
            result = orderService.insertSelective(order, getUserBySession());
            request.setAttribute(Contants.MESSAGE, result.getMessage());
        } catch (Exception e) {
            logger.error("addOrder error:{}", e);
            request.setAttribute(Contants.MESSAGE, "订单已存在!");
        }
        request.setAttribute(Contants.OBJECT, order);
        logger.info("result:{}", JSON.toJSONString(result));
        return "order-add";
    }

    @ResponseBody
    @RequestMapping(value = "deleteOrder", produces = {"text/json;charset=UTF-8"})
    public String deleteOrder(OrderVo orderVo) {
        logger.info("orderVo:{}", JSON.toJSONString(orderVo));
        Result<Order> result = orderService.deleteByPrimaryKey(orderVo, getUserBySession());
        logger.info("result:{}", JSON.toJSONString(result));
        return JSON.toJSONString(result);
    }

    @RequestMapping("orderModify")
    public String orderModify(OrderVo orderVo) {
        logger.info("orderVo:{}", JSON.toJSONString(orderVo));
        Result<Order> result = orderService.selectByPrimaryKey(orderVo.getOrderId(), getUserBySession());
        request.setAttribute(Contants.OBJECT, result.getData());
        logger.info("result:{}", JSON.toJSONString(result));
        return "order-modify";
    }

    @RequestMapping("updateOrder")
    public String updateOrder(Order order) {
        order.setCreateTime(DateUtil.getInstance().getDateByString(order.getCreateTimeString()));
        logger.info("order:{}", JSON.toJSONString(order));
        Result<Order> result = orderService.updateByPrimaryKeySelective(order, getUserBySession());
        request.setAttribute(Contants.MESSAGE, result.getMessage());
        request.setAttribute(Contants.OBJECT, order);
        logger.info("result:{}", JSON.toJSONString(result));
        return "order-modify";
    }

    @RequestMapping("orderShow")
    public String orderShow(Long id) {
        Result<Order> result = orderService.selectByPrimaryKey(id, getUserBySession());
        request.setAttribute(Contants.OBJECT, result.getData());
        logger.info("result:{}", JSON.toJSONString(result));
        return "order-show";
    }

    @RequestMapping("orderCount")
    public String orderCount(OrderVo orderVo) {
        logger.info("orderVo:{}", JSON.toJSONString(orderVo));
        Result<List<Order>> result = orderService.selectByExample(orderVo, getUserBySession());
        request.setAttribute(Contants.ORDERS, result.getData());
        request.setAttribute(Contants.OBJECT, orderVo);
        logger.info("result:{}", JSON.toJSONString(result));
        return "order-count";
    }

    @ResponseBody
    @RequestMapping(value = "exportData")
    public String exportData(OrderVo orderVo) throws Exception {
        logger.info("orderVo:{}", JSON.toJSONString(orderVo));
        String randomDate = String.valueOf(new Date().getTime());
        String filePath = ExportExcel.exportExcel(Contants.FILE_NAME + randomDate, Contants.FILE_NAME + randomDate, Contants.ORDER_EXPORT_HEADER, response,
                new ExportExcel.IDataWriteCallBack() {
                    @Override
                    public void writeData(WritableSheet sheet, WritableWorkbook wwb) throws Exception {
                        Result<List<Order>> result = orderService.selectByExample(orderVo, getUserBySession());
                        logger.info("result:{}", JSON.toJSONString(result));
                        if (CollectionUtils.isEmpty(result.getData())) {
                            return;
                        }
                        jxl.write.NumberFormat nf = new jxl.write.NumberFormat("#0.00"); // 设置数字格式
                        jxl.write.WritableCellFormat wcfN = new jxl.write.WritableCellFormat(nf); // 设置表单格式
                        for (int i = 0; i < result.getData().size(); i++) {
                            int j = 0;
                            sheet.addCell(new Label(j++, i + 1, result.getData().get(i).getId() + ""));
                            sheet.addCell(new Label(j++, i + 1, result.getData().get(i).getUserId() + ""));
                            sheet.addCell(new Label(j++, i + 1, result.getData().get(i).getName()));
                            sheet.addCell(new Label(j++, i + 1, result.getData().get(i).getWw()));
                            sheet.addCell(new Label(j++, i + 1, result.getData().get(i).getGameName()));
                            sheet.addCell(new Label(j++, i + 1, result.getData().get(i).getServiceArea()));
                            sheet.addCell(new Label(j++, i + 1, result.getData().get(i).getContent()));
                            sheet.addCell(new Label(j++, i + 1, result.getData().get(i).getCreateTimeString()));
                            /*sheet.addCell(new Label(j++, i + 1, result.getData().get(i).getAllTime() + ""));*/
                            sheet.addCell(new Label(j++, i + 1, result.getData().get(i).getTypeString()));
                            sheet.addCell(new Label(j++, i + 1, result.getData().get(i).getRemark()));
//                            sheet.addCell(new Label(j++, i + 1, result.getData().get(i).getOrderPrice() + ""));
//                            sheet.addCell(new Label(j++, i + 1, result.getData().get(i).getSettlePrice() + ""));
                            sheet.addCell(new jxl.write.Number(j++, i + 1,result.getData().get(i).getOrderPrice().longValue(), wcfN));// 格式化数值
                            sheet.addCell(new jxl.write.Number(j++, i + 1,result.getData().get(i).getSettlePrice().longValue(), wcfN));// 格式化数值
                        }
                    }
                });
        InputStream is = new FileInputStream(new File(filePath));
        OutputStream os = response.getOutputStream();
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + Contants.FILE_NAME + "order" + randomDate + ".xlsx");

            byte[] b = new byte[2048];
            int length;
            while ((length = is.read(b)) > 0) {
                os.write(b, 0, length);
            }
            os.close();
            is.close();
        } catch (Exception e) {
            logger.info("exportData error:{}", e);
        } finally {
            if (is != null) {
                is.close();
            }
            if (os != null) {
                os.close();
            }
        }
        //  返回值要注意，要不然就出现下面这句错误！
        //java+getOutputStream() has already been called for this response
        return null;

    }

}
